<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>数据劫持</title>
  </head>
  <body>
    <script>
      const vm = {
        _data: {
          name: "张三",
          age: 18,
          sex: null,
          hobby: ["抽烟", "喝酒"],
        },
      };

      function detectionDataType(targetObj) {
        return Object.prototype.toString.call(targetObj).slice(8, -1);
      }

      function defineReactive(targetObj, key, value) {
        observe(value);
        Object.defineProperty(targetObj, key, {
          get() {
            return value;
          },
          set(newVal) {
            value = newVal;
          },
        });
      }

      function observe(targetObj) {
        console.log(detectionDataType(targetObj));
        // 判断 targetObj 是否可以添加响应式
        /* if (
          detectionDataType(targetObj) !== "Object" &&
          detectionDataType(targetObj) !== "Array"
        )
          return; */

        if (detectionDataType(targetObj) !== "Object") return;

        for (const [key, value] of Object.entries(targetObj)) {
          // console.log(key, value)  自己代理自己，所以要将 value 提前取出
          defineReactive(targetObj, key, value);
        }
      }

      observe(vm._data);
    </script>
  </body>
</html>
